#!/usr/bin/python3
# -* - coding: UTF-8 -* -

'''
Cookie管理
'''

import os
import pickle
import sys
import threading
from urllib.parse import quote

import requests
from selenium.webdriver.common.by import By

from data import Config
from selenium_utils.ElementGps import ElementGps
from selenium_utils.ElementOperate import ElementOperate

curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

from utils import LogSys

mutex = threading.Lock()


def read_cookies(app):
    # 读取
    try:
        if not os.path.exists('./{}.pkl'.format(get_file_name(app))):
            print('文件不存在，需要先创建')
            save_cookies({}, app)
        f_read = open('./{}.pkl'.format(get_file_name(app)), 'rb')
        dict2 = pickle.load(f_read)
        f_read.close()
        LogSys.logInfo("get Cookie:{0}".format(dict2))
        return dict2
    except UnboundLocalError as e:
        return {}
    except FileNotFoundError as FileNotFoundError:

        return {}


def assert_is_have_new_cookies(jsonData, app):
    # 读取

    f_read = open('./{}.pkl'.format(get_file_name(app)), 'rb')
    saveJson = pickle.load(f_read)
    f_read.close()
    if saveJson == jsonData:
        return False
    return saveJson


def save_cookies(jsonData, app):
    # 字典保存
    mutex.acquire(10)
    f_save = open('./{}.pkl'.format(get_file_name(app)), 'wb')
    LogSys.logInfo("save Cookie:{0}".format(jsonData))
    pickle.dump(jsonData, f_save)
    f_save.close()
    mutex.release()


def cookie_for_ylt(res):
    resc = res.json()['data']
    print(resc)
    cookieJson = res.cookies.get_dict()
    print(cookieJson)
    cookieJson['state'] = resc['state']
    cookieJson['roles'] = resc['roles'][0]
    print(resc['name'])
    print(type(resc['name']))
    cookieJson['name'] = quote(resc['name'], safe='/', encoding=None, errors=None)
    cookieJson['enterpriseId'] = resc['enterpriseId']
    cookieJson['hasTransactionPassword'] = 'true'
    cookieJson['enterpriseCategory'] = resc['roles'][0].split(':')[0]
    strCookie = ""
    for k, v in cookieJson.items():
        strCookie = strCookie + '{}={}'.format(k, v) + ";"
    LogSys.logInfo('cookie:{}'.format(strCookie))
    return strCookie


def cookie_for_reirp(res, request):
    resc = res.json()['data']
    cookieJson = res.cookies.get_dict()

    cookieJson['state'] = resc['state']
    cookieJson['roleCode'] = resc['roleCode']
    cookieJson['name'] = quote(resc['name'], safe='/', encoding=None, errors=None)
    cookieJson['enterpriseId'] = resc['enterpriseId']

    strCookie = ""
    for k, v in cookieJson.items():
        strCookie = strCookie + '{}={}'.format(k, v) + ";"

    res = request._get_for_self(api='api/system/user/current', headers={'cookie': strCookie})
    resc = res['data']
    strCookie = strCookie + '{}={}'.format('enterpriseLevel', resc['enterpriseLevel']) + ";"
    LogSys.logInfo('cookie:{}'.format(strCookie))
    return strCookie

def cookie_for_reirp2(res, request):
    resc = res.json()['data']
    cookieJson = res.cookies.get_dict()

    cookieJson['state'] = resc['state']
    cookieJson['roleCode'] = resc['roleCode']
    cookieJson['name'] = quote(resc['name'], safe='/', encoding=None, errors=None)
    cookieJson['enterpriseId'] = resc['enterpriseId']

    strCookie = ""
    for k, v in cookieJson.items():
        strCookie = strCookie + '{}={}'.format(k, v) + ";"

    res = request._get_for_self(api='api/system/user/current', headers={'cookie': strCookie})
    resc = res['data']
    strCookie = strCookie + '{}={}'.format('enterpriseLevel', resc['enterpriseLevel']) + ";"
    LogSys.logInfo('cookie:{}'.format(strCookie))
    return strCookie


def cookie_for_hn_reirp(res, request):
    resc = res.json()['data']
    cookieJson = res.cookies.get_dict()

    # cookieJson['state'] = resc['state']
    # cookieJson['roleCode'] = resc['roleCode']
    # cookieJson['name'] = resc['name'].encode('UTF-8')
    # cookieJson['enterpriseId'] = resc['enterpriseId']

    strCookie = ""
    for k, v in cookieJson.items():
        strCookie = strCookie + '{}={}'.format(k, v) + ";"

    # res = request._get_for_self(api='api/system/user/current', headers={'cookie': strCookie})
    # resc = res['data']
    # strCookie = strCookie + '{}={}'.format('enterpriseLevel', resc['enterpriseLevel']) + ";"
    LogSys.logInfo('cookie:{}'.format(strCookie))
    return strCookie


def set_cookie_for_ylt(driver, user,cookies=None):
    gps = ElementGps()
    operate = ElementOperate()

    operate.input(gps.find_element(By.ID, 'custom-validation_phone'),user.get_user_value())
    operate.input(gps.find_element(By.ID, 'custom-validation_password'),user.get_password_value())
    operate.click(gps.button('登 录'))
    '''
    post登录设置cookies
    :param url:
    :param data:
    :param headers:
    :param cookies:
    :return:
    '''
    # for item in cookies.split(';'):
    #     if '=' not in item:
    #         return
    #     kvlist = item.split('=')
    #     if kvlist[0] == 'JSESSIONID':
    #         i = {'domain': '.ycfin.net', 'name': kvlist[0], 'value': kvlist[1], 'path': '/', 'httpOnly': True,
    #              'secure': True}
    #         driver.add_cookie(i)
    #     elif kvlist[0] == 'name':
    #         i = {'name': kvlist[0],
    #              'value': kvlist[1], 'path': '/'
    #              }
    #         driver.add_cookie(i)
    #     else:
    #         i = {'name': kvlist[0], 'value': str(kvlist[1]), 'path': '/'
    #              }
    #         driver.add_cookie(i)


def set_cookie_for_reirp(driver, cookies=None):
    '''
    post登录设置cookies
    :param url:
    :param data:
    :param headers:
    :param cookies:
    :return:
    '''
    for item in cookies.split(';'):
        if '=' not in item:
            return
        kvlist = item.split('=')
        if kvlist[0] == 'JSESSIONID':
            i = {'domain': '10.211.4.108', 'name': kvlist[0], 'value': kvlist[1], 'path': '/api', 'httponly': True}
        else:
            i = {'domain': '10.211.4.108', 'name': kvlist[0], 'value': str(kvlist[1]), 'path': '/'}
        driver.add_cookie(i)


def set_cookie_for_hn_reirp(driver, cookies=None):
    '''
    post登录设置cookies
    :param url:
    :param data:
    :param headers:
    :param cookies:
    :return:
    '''
    for item in cookies.split(';'):
        if '=' not in item:
            return
        kvlist = item.split('=')
        if kvlist[0] == 'JSESSIONID':
            i = {'domain': '10.211.4.108', 'name': kvlist[0], 'value': kvlist[1], 'path': '/api', 'httponly': 'true'}
        else:
            i = {'domain': '10.211.4.108', 'name': kvlist[0], 'value': str(kvlist[1]), 'path': '/'}
        driver.add_cookie(i)


def get_file_name(app):
    if app == Config.APP_YLT:
        fileName = 'cookieYlt'
    elif app == Config.APP_REIRP:
        fileName = 'cookieReirp'
    elif app == Config.APP_HN_REIRP:
        fileName = 'cookieHNReirp'

    return fileName
